const express = require('express')
const { authenticateToken } = require('../middleware/auth')
const logger = require('../utils/logger')
const { HTTP_STATUS } = require('../utils/constants')

const router = express.Router()

// DeepSeek API调用接口
router.post('/chat', async (req, res) => {
  console.log('=== AI Chat API 请求开始 ===');
  console.log('请求方法:', req.method);
  console.log('请求路径:', req.path);
  console.log('请求头:', JSON.stringify(req.headers, null, 2));
  console.log('请求体:', JSON.stringify(req.body, null, 2));
  
  // 在try块外部定义变量，确保在catch块中也能访问
  let model, numericTemperature, numericMaxTokens, messages
  
  try {
    const requestData = req.body
    console.log('解析请求数据:', JSON.stringify(requestData, null, 2));
    model = requestData.model || 'deepseek-chat'
    const temperature = requestData.temperature || 0.7
    const max_tokens = requestData.max_tokens || 8000
    const apiKey = requestData.apiKey
    const apiUrl = requestData.apiUrl
    messages = requestData.messages
    
    // 确保数值参数为正确类型
    numericTemperature = typeof temperature === 'string' ? parseFloat(temperature) : temperature
    numericMaxTokens = typeof max_tokens === 'string' ? parseInt(max_tokens) : max_tokens
    
    console.log('处理后的参数:');
    console.log('- model:', model);
    console.log('- temperature:', numericTemperature);
    console.log('- max_tokens:', numericMaxTokens);
    console.log('- apiKey存在:', !!apiKey);
    console.log('- apiUrl:', apiUrl);
    console.log('- messages数量:', messages?.length);
    
    if (!messages || !Array.isArray(messages)) {
      console.log('错误: 消息格式不正确');
      return res.status(HTTP_STATUS.BAD_REQUEST).json({
        success: false,
        message: '消息格式不正确'
      })
    }
    
    if (!apiKey) {
      console.log('错误: API密钥不能为空');
      return res.status(HTTP_STATUS.BAD_REQUEST).json({
        success: false,
        message: 'API密钥不能为空'
      })
    }
    
    console.log('参数验证通过，准备调用AI API');
    
    logger.info('DeepSeek API调用开始', {
      model,
      messageCount: messages.length
    })
    
    // 动态导入OpenAI SDK
    console.log('开始导入OpenAI SDK');
    const { default: OpenAI } = await import('openai')
    console.log('OpenAI SDK导入成功');
    
    // 使用用户配置的apiUrl，如果没有则使用默认的DeepSeek API
    let baseURL = 'https://api.deepseek.com/v1'
    if (apiUrl) {
      // 如果用户传入的是完整的API端点，提取baseURL
      if (apiUrl.includes('/chat/completions')) {
        baseURL = apiUrl.replace('/chat/completions', '')
      } else {
        baseURL = apiUrl
      }
    }
    console.log('使用的API基础URL:', baseURL);
    
    console.log('创建OpenAI客户端实例');
    const openai = new OpenAI({
      baseURL: baseURL,
      apiKey: apiKey,
      timeout: 360000 // 6分钟超时
    })
    console.log('OpenAI客户端创建成功');
    
    console.log('准备调用chat.completions.create');
    console.log('调用参数:', {
      messages: messages,
      model: model,
      temperature: numericTemperature,
      max_tokens: numericMaxTokens
    });
    
    const completion = await openai.chat.completions.create({
      messages,
      model,
      temperature: numericTemperature,
      max_tokens: numericMaxTokens
    })
    
    console.log('API调用成功，收到响应:', JSON.stringify(completion, null, 2));
    
    const assistantMessage = completion.choices[0]?.message?.content || '抱歉，我无法回答这个问题。'
    console.log('提取的助手消息:', assistantMessage);
    console.log('使用情况:', completion.usage);
    
    logger.info('DeepSeek API调用成功', {
      model,
      responseLength: assistantMessage.length
    })
    
    const responseData = {
      success: true,
      data: {
        message: assistantMessage,
        usage: completion.usage
      }
    };
    
    console.log('准备返回响应:', JSON.stringify(responseData, null, 2));
    res.json(responseData);
    console.log('=== AI Chat API 请求完成 ===');
    
  } catch (error) {
    console.log('=== AI Chat API 发生错误 ===');
    console.log('错误类型:', error.constructor.name);
    console.log('错误消息:', error.message);
    console.log('错误代码:', error.code);
    console.log('错误堆栈:', error.stack);
    console.log('请求参数:', {
      model,
      temperature: numericTemperature,
      max_tokens: numericMaxTokens,
      messageCount: messages?.length
    });
    
    // 详细的错误日志记录
    logger.error('DeepSeek API调用失败', {
      error: error.message,
      stack: error.stack,
      errorCode: error.code,
      errorType: error.constructor.name,
      requestData: {
        model,
        temperature: numericTemperature,
        max_tokens: numericMaxTokens,
        messageCount: messages?.length
      }
    })
    
    // 根据错误类型返回更具体的错误信息
    let errorMessage = 'AI服务调用失败'
    if (error.message.includes('timeout')) {
      errorMessage = 'AI服务响应超时，请稍后重试'
    } else if (error.message.includes('network')) {
      errorMessage = '网络连接失败，请检查网络设置'
    } else if (error.message.includes('401') || error.message.includes('unauthorized')) {
      errorMessage = 'API密钥无效或已过期'
    } else if (error.message.includes('429')) {
      errorMessage = 'API调用频率超限，请稍后重试'
    } else if (error.message.includes('400')) {
      errorMessage = '请求参数错误，请检查输入内容'
    }
    
    res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({
      success: false,
      message: `${errorMessage}: ${error.message}`
    })
  }
})

module.exports = router